<template>
    <el-form ref="addTictData" :rules="rules" :model="addTictData"
             class="addTictStyle"
             label-position="top"  size="small">
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
      <h3 class="ticTitle">票务基本信息</h3>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票务名称 :" prop="name">
            <el-input v-model="addTictData.name" placeholder="请输入票务名称" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票务种类 :" prop="tictKind" >
            <el-select v-model="addTictData.tictKind" filterable placeholder="请选择票务种类" style="width:100%">
              <el-option
                v-for="kinds in tickValue"
                :key="kinds.code"
                :label="kinds.name"
                :value="kinds.code"
              >{{kinds.name}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="所属场馆 :" prop="yardName">
            <el-select v-model="addTictData.yardName" filterable placeholder="请选择场地"   @change='getValue' style="width:100%">
              <el-option
                v-for="item in yardOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code">
                {{item.name}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="场地代码 :" prop="yardCode" hidden>
            <el-input v-model="addTictData.yardCode" placeholder="选择场地后自动填充" disabled ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票代码 :" prop="code" hidden>
            <el-input v-model="addTictData.code" placeholder="请输入票代码" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="商户UUID :" prop="merchUuid" v-show="false">
            <el-input v-model="addTictData.merchUuid" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="商户信息 :" prop="merchName">
            <el-input v-model="addTictData.merchName" placeholder="商户名称"   ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="验证方式 :" prop="validation">
            <el-select v-model="addTictData.validation" filterable placeholder="请选择验证方式" style="width:100%"  multiple>
              <el-option v-for="validation in validationOptions"
                         :key="validation.code"
                         :label="validation.name"
                         :value="validation.code">
                {{validation.name}}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
<!--        <el-col :span="10">-->
<!--          <el-form-item label="票据状态 :" prop="valid">-->
<!--            <el-select v-model="addTictData.valid" filterable placeholder="请票据状态" style="">-->
<!--              <el-option-->
<!--                v-for="( ky, val ) in validOptions"-->
<!--                :key="val"-->
<!--                :label="ky"-->
<!--                :value="val">-->
<!--                {{ky}}-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="退票 :" prop="recedeTick">
            <el-switch
              v-model="addTictData.recedeTick"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="100"
              inactive-value="0"
              @change='checkRecedeTick'
             >
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item  label="可退日期 :" prop="recedeDate" v-if="this.addTictData.recedeTick==100" >
            <el-date-picker
              v-model="addTictData.recedeDate"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm:ss"
              style="width:100%"
               >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
        <el-form-item label="票面图片 :">
          <el-upload ref="upload" action="''"
                     list-type="picture-card"
                     :file-list="showImgs"
                     :auto-upload="false"
                     :http-request="uploadFile"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="票务介绍 :" prop="info" >
            <el-input v-model="addTictData.info" placeholder="请输入票信息" type="textarea" ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
        <el-form-item label="详情图 :">
          <el-upload ref="detailUpload" action="''"
                     list-type="picture-card"
                     :file-list="detailShowImgs"
                     :auto-upload="false"
                     :http-request="uploadFileDeatail"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
        <el-form-item label="轮播图 :">
          <el-upload ref="carouseUpload" action="''"
                     list-type="picture-card"
                     :file-list="carouselShowImgs"
                     :auto-upload="false"
                     :http-request="uploadFileCarouse"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        </el-col>
      </el-row>
      <el-footer height="80px">
        <el-row style="display: flex;justify-content: center;align-items: center;">
          <el-button @click="submit" type="primary" size="small">
            保存
          </el-button>
          <el-button @click="editOut" size="small">
            取消
          </el-button>
        </el-row>
      </el-footer>
    </el-form>

</template>

<script>
import { replaceSpacesObj } from '../../../utils/webUtils.js'
import {}  from "../../../styles/addTict.scss"

export default {
  name: 'AddTict',
  components: {  },
  data() {
    return {
      addTictData: {
        name: '',
        code: '',
        yardName: '',
        yardCode: '',
        info: '',
        merchUuid: '',
        merchName: '',
        valid: '',
        tictKind: '',
        validation: [],
        recedeDate: '',
        recedeTick: '',
        imgStr:'',
        detailImgStr:'',
        carouseImgStr:''
      },

      validOptions: {},
      yardOptions: [],
      mercList: [],
      merchants: { name: '', uuid: '' },
      tickValue: [],
      validationOptions: [],
      showImgs:[],
      list:[],
      detailShowImgs:[],
      detailList:[],
      carouselShowImgs:[],
      carouseList:[],
      rules: {
        name: [
          { required: true, message: '票名称不能为空', trigger: 'blur' },
        ],
        tictKind: [
          { required: true, message: '票务种类不能为空', trigger: 'blur' },
        ],
        yardName: [
          { required: true, message: '所属场馆不能为空', trigger: 'blur' },
        ],
        validation: [
          { required: true, message: '验证方式不能为空', trigger: 'blur' },
        ],
      },
      info: '',
      infoShow: false,
      imgList: [],
      imgformData: {},
      editBoxShow: false,
      addShow: false,
      displayDate: false,
      uuid: ''
    }
  },
  mounted() {
    this.queryValid()
    this.queryYard()
    this.queryMerch()
    // 票务种类
    this.queryKinds()
    // 验证方式
    this.queryvalidationOptions()
  },
  created(){

  },
  methods: {
    imgState(msg) {
      this.editBoxShow = msg
      this.editShow = msg
      this.addShow = msg
    },
    clean() {
      this.addTictData = {}
    },
    checkRecedeTick() {
      if (this.addTictData.recedeTick == '0') {
        this.addTictData.recedeDate = ''
      }
    },
    // 依据当前用户查询商户信息
    queryMerch() {
      this.axios
        .request({
          method: 'get',
          url: './ope/kdi/merch/search/findByUser',
          params: {}
        })
        .then(response => {
          this.mercList = response.data
          this.merchants = response.data[0]
          this.addTictData.merchUuid = this.merchants.uuid
          this.addTictData.merchName = this.merchants.name
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 查询后端票据有效标识枚举
    queryValid() {
      this.axios
        .request({
          method: 'get',
          url: './tck/kdi/enums/Valid',
          params: {}
        })
        .then(response => {
          this.validOptions = response.data.data
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 票务种类
    queryKinds() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_KINDS',
          params: {}
        })
        .then(response => {
          this.tickValue = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 票务验证方式
    queryvalidationOptions() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_VOLIDATION',
          params: {}
        })
        .then(response => {
          this.validationOptions = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 查询场地
    queryYard() {
      this.axios
        .request({
          method: 'get',
          url: './ope/kdi/yard/search/findAllTree',
          params: {}
        })
        .then(response => {
          this.yardOptions = response.data[0].subs
        })
        .catch(error => {
          console.log(error)
        })
    },
    getValue() {
      this.yardOptions.forEach(list => {
        if (list.name === this.addTictData.yardName) {
          this.addTictData.yardCode = list.code
        }
      })
    },
    addTict() {
      this.editBoxShow = true
      this.addShow = true
      this.editShow = false
    },
    uploadFileCarouse(item){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "http://39.106.30.94/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        var data=res.data.data;
        this.carouseList.push({'filename':data.filename,'url':data.url})
        this.addTictData.carouseImgStr = JSON.stringify(this.carouseList)
        if(this.addTictData.carouseImgStr.length>0){
          this.uploadImg();
          this.dataSucess("上传轮播图成功")
        }
      }).catch(error => {
        console.log(error);
        this.dataFail("上传轮播图失败")
      });
    },
    uploadFile(item){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "http://39.106.30.94/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        var data=res.data.data;
        this.list.push({'filename':data.filename,'url':data.url})
        this.addTictData.imgStr = JSON.stringify(this.list)
        if(this.addTictData.imgStr.length>0){
          this.uploadImg();
          this.dataSucess("上传票面图片成功")
        }
      }).catch(error => {
        this.dataFail("上传票面图片失败")
      });
    },
    uploadFileDeatail(item){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "http://39.106.30.94/tck/kdi/tict/"+this.uuid+"/imgup",formData
      ).then(res=>{
        var data=res.data.data;
        this.detailList.push({'filename':data.filename,'url':data.url})
        this.addTictData.detailImgStr = JSON.stringify(this.detailList)
        if(this.addTictData.detailImgStr.length>0){
          this.uploadImg();
          this.dataSucess("上传详情图成功")
        }
      }).catch(error => {
        console.log(error);
        this.dataFail("上传详情图失败")
      });
    },
    submit() {
      this.$refs['addTictData'].validate((valid) => {
        if (!valid) {
          return ;
        }
        this.addTictData = replaceSpacesObj(this.addTictData)
        this.axios.request({
          method: 'post',
          url: './tck/kdi/tict',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: {
            name: this.addTictData.name,
            code: this.addTictData.code,
            yardName: this.addTictData.yardName,
            yardCode: this.addTictData.yardCode,
            info: this.addTictData.info,
            merchUuid: this.addTictData.merchUuid,
            merchName: this.addTictData.merchName,
            // valid: this.addTictData.valid,
            validation: JSON.stringify(this.addTictData.validation),
            tictKind: this.addTictData.tictKind,
            recedeTick: this.addTictData.recedeTick,
            recedeDate: this.addTictData.recedeDate

          }
        }).then(response => {
          this.uuid = response.data.data.uuid
          this.dataSucess("新增数据成功");
          this.imgSubmit();
        this.closDisplay()

        }).catch(error => {
          console.log(error)
          this.info = '票务新增失败'
          this.dataFail("新增数据失败");
        })
      })
    },
    closDisplay(){
      this.$router.push("/tictReport")
    },
    dataSucess(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success'
      });
    },
    dataFail(message) {
      this.$notify({
        title: '失败',
        message: message,
        type: 'error'
      });
    },
    imgSubmit(){
      if(this.showImgs.length>0){
        this.showImgs.forEach(res=>{
          this.list.push({'filename':res.name,'url':res.url.substr(res.url.lastIndexOf('tict'))})
        })
        this.addTictData.imgStr = JSON.stringify(this.list)
      }else if (this.detailShowImgs.length>0){
        this.detailShowImgs.forEach(res=>{
          this.detailList.push({'filename':res.name,'url':res.url.substr(res.url.lastIndexOf('tict'))})
        })
        this.addTictData.detailImgStr=JSON.stringify(this.detailList)
      }else if(this.carouselShowImgs.length>0) {
        this.carouselShowImgs.forEach(res => {
          this.carouseList.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('tict'))})
        })
        this.addTictData.detailImgStr = JSON.stringify(this.carouseList)
      } else{
        this.addTictData.imgStr = ''
        this.addTictData.detailImgStr=''
        this.addTictData.carouseImgStr=''
      }
      this.$refs.detailUpload.submit()
      this.$refs.upload.submit()
      this.$refs.carouseUpload.submit()


    },
    //图片上传

    uploadImg(){
      this.axios.request({
        method: "put",
        url: "./tck/kdi/tict/"+this.uuid+"/img",
        headers: {
          "Content-Type": "application/json;charset=UTF-8"
        },
        data: {
          detailImgStr:this.addTictData.detailImgStr,
          carouseImgStr:this.addTictData.carouseImgStr,
          imgStr:this.addTictData.imgStr,
        }
      }).then(() => {
      }).catch(error => {
        console.log(error);
        this.info = '上传图片后回写imgStr数据失败！';
        this.infoShow = true;
        this.dataFail("上传图片回写数据失败")
      });
    },
    endProcessing(infoShow) {
      this.info = this.info + '新增成功,两秒后关闭'
      this.infoShow = true
      setTimeout(() => {
        this.infoShow = false
        this.$emit("close")
        this.info = ''
      }, 2000)
    },
    cleanHrom() {
      this.addTictData = {
        name: '',
        code: '',
        yardName: '',
        yardCode: '',
        info: '',
        merchUuid: '',
        merchName: '',
        valid: '',
        tictKind: '',
        validation: '',
        recedeDate: '',
        recedeTick: '',
        detailImgStr:'',
        carouseImgStr:''
      }



    },
    editOut() {
      this.$router.push('/tictReport')
    }
  }
}
</script>

<style scoped lang="scss">
  .edit{
    width: 1000px;
    height: 100%;
    z-index: 100;
  }


</style>
